package top.zhenganwen.securitydemo.web.controller;

import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;

/**
 * @author zhenganwen
 * @date 2019/8/21
 * @desc FileController
 */
@RestController
@RequestMapping("/file")
public class FileController {

    public static final String FILE_STORE_FOLDER = "C:\\Users\\zhenganwen\\Desktop\\";

    @PostMapping
    public String upload(MultipartFile file) throws IOException {

        System.out.println("[FileController]文件请求参数: " + file.getName());
        System.out.println("[FileController]文件名称: " + file.getName());
        System.out.println("[FileController]文件大小: "+file.getSize()+"字节");


        String fileKey = new Date().getTime() + "_" + file.getOriginalFilename();
        File storeFile = new File(FILE_STORE_FOLDER, fileKey);

        // 可以通过file.getInputStream将文件上传到FastDFS、云OSS等存储系统中
//        InputStream inputStream = file.getInputStream();
//        byte[] content = new byte[inputStream.available()];
//        inputStream.read(content);

        file.transferTo(storeFile);

        return fileKey;
    }

    @GetMapping("/{fileKey:.+}")
    public void download(@PathVariable String fileKey, HttpServletResponse response) throws IOException {

        try (
                InputStream is = new FileInputStream(new File(FILE_STORE_FOLDER, fileKey));
                OutputStream os = response.getOutputStream()
        ) {
            // 下载需要设置响应头为 application/x-download
            response.setContentType("application/x-download");
            // 设置下载询问框中的文件名
            response.setHeader("Content-Disposition", "attachment;filename=" + fileKey);

            IOUtils.copy(is, os);
            os.flush();
        }
    }
}
